<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      <div class="btns">
        <button data-path="news">新闻</button>
        <button data-path="play">娱乐</button>
        <button data-path="game">游戏</button>
      </div>
      <div class="container"></div>
    </div>
  </body>
</html>
<script>
  const EleContainer = document.querySelector('.container');

  // 1.书写一个路由表，在实现路由的时候，按照这个路由表的映射关系决定
  const routers = [
    { path: '/news', content: '新闻模块' },
    { path: '/play', content: '娱乐模块' },
    { path: '/game', content: '游戏模块' },
  ];

  const EleBtns = document.querySelectorAll('.btns button');
  // 2.给每一个导航绑定点击事件，可以根据导航上的属性，跳转到指定的hash地址
  for (var i = 0; i < EleBtns.length; i++) {
    EleBtns[i].onclick = function () {
      location.hash = '#' + this.dataset.path;
    };
  }

  // 3. 监听hash的改变，根据路由表加载对应的视图
  window.onhashchange = function () {
    // console.log('变了', location.hash);
    routers.forEach((item) => {
      if (item.path.slice(1) === location.hash.slice(1)) {
        EleContainer.textContent = item.content;
      }
    });
  };
</script>
